<template>
	<view class="container">

		<uni-search-bar v-if="!showSelect" placeholder="请输入商品名称" :focus="true" v-model="name" @confirm="searchByName"
			@input="searchByName" cancelButton="none">
		</uni-search-bar>

		<!-- 商品列表 -->
		<view class="data-list">
			<view v-for="(item, rowIndex) in datalist" :key="rowIndex">
				<view v-if="!showSelect || ( showSelect && selectGoods[item.goodsId]) " class="data-item">
					<img :src="goodImage(item)" @click="goToDetail(item)" class="data-image"
						@error="handleImageError(item)" />
					<view class="data-info" @click="goToDetail(item)">
						<text class="data-name">{{ item.name }}</text>
						<text class="data-info-detail">
							<text>库存:{{ item.stockCurrent }}</text>
						</text>
						<text class="data-info-detail">
							价格:￥{{ item.price }}
						</text>
					</view>
					<view @click="addToOrderList">

					</view>
					<view v-if="!selectGoods[item.goodsId]">
						<image @click="addToOrderList(item)" class="add-image" src="/static/add.png"></image>
					</view>
					<view v-else>
						<uni-number-box v-model="selectGoods[item.goodsId].buyNum"
							@change="changeValue(selectGoods[item.goodsId])" :min="0"
							:max="item.stockCurrent"></uni-number-box>
					</view>
				</view>
			</view>
		</view>

		<view class="price_info">
			已选 {{options[0].info}} 件，总价：￥{{sumprice}}
		</view>
		<uni-goods-nav :fill="true" :options="options" :button-group="customButtonGroup" @click="onClick"
			@buttonClick="buttonClick" />

		<!-- 修改数量的弹窗 -->
		<uni-popup ref="editPopup" type="dialog">
			<view class="out-popup">
				<view class="out-popup-title"> 商品出库 </view>
				<view class="out-popup-num">
					<text>会员ID：</text>
					<uni-input v-model="user_id"></uni-input>
				</view>
				<view class="out-popup-num">
					<text>出库数量：</text>
					<uni-number-box :min="0" :max="max" v-model="editQuantity" />
				</view>
				<view class="out-popup-btn">
					<button class="btn cancel" @click="cancelEdit()">取消</button>
					<button class="btn config" @click="confirmEdit()">确认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	import fjjCondition from '@/components/fjj-condition/fjj-condition.vue';
	import filterData from '@/common/data/goods/goods_filter.js';
	import dataDictionary from '@/common/data/dataDictionary.js';
	export default {
		data() {
			return {
				color: '#4D7BFE',
				hasChoose: false,
				defaultValue: {},
				filterData: filterData,
				datalist: [],
				goodsOpt: dataDictionary.goods,
				sourceOpt: {},
				statusOpt: {},
				name: '',
				searchParam: {
					name: '',
					storeId: 1,
				},
				defaultImage: '/static/no_image.png',
				isEdit: false,
				isOrder: false,
				customButtonGroup: [{
					text: '下单',
					backgroundColor: 'linear-gradient(90deg, #1E83FF, #0053B8)',
					color: '#fff'
				}],
				options: [{
					icon: 'cart',
					text: '购买清单',
					info: 0
				}],
				selectGoods: {

				},
				showSelect: false,
				sumprice: 0
			};
		},
		components: {
			fjjCondition,
		},
		
		computed: {
			...mapGetters({
				userInfo: 'user/info',
				hasLogin: 'user/hasLogin'
			}),
		},
		
		onLoad(option) {
			if (option && option.isOrder) {
				this.isOrder = option.isOrder;
			}
			// 初始上商品详情里面的枚举值
			if (this.goodsOpt) {
				let sourceOpts = this.goodsOpt.source;
				for (let i = 0; i < sourceOpts.length; i++) {
					this.sourceOpt[sourceOpts[i].value] = sourceOpts[i].text;
				}

				let statusOpts = this.goodsOpt.status;
				for (let i = 0; i < statusOpts.length; i++) {
					this.statusOpt[statusOpts[i].value] = statusOpts[i].text;
				}
			}
			this.searchParam.storeId = this.userInfo.storeId;
			// 初始化过滤值
			this.initFilterData();
			this.onSearch();
			this.selectGoods = uni.getStorageSync('orderGoods') || {};
			this.options[0].info = Object.keys(this.selectGoods).length;
			this.sumSelectPrice();
		},

		onShow() {
			this.onSearch();
		},

		computed: {

		},

		methods: {

			goodImage(item) {
				if (item.image) {
					return this.$urlConfig + '/api/images/' + item.image;
				}
				return this.$urlConfig + '/api/images/' + this.defaultImage;
			},


			handleImageError(item) {
				item.image = this.defaultImage;
			},

			// 使用 computed 属性处理 value 的默认值
			sumSelectPrice() {
				let price = 0;
				Object.keys(this.selectGoods).forEach(key => {
					price = price + this.selectGoods[key].buyNum * this.selectGoods[key].price
				})
				this.sumprice = price;
			},

			async initFilterData() {
				if (this.filterData && this.goodsOpt) {
					for (let i = 0; i < this.filterData.length; i++) {
						if (this.goodsOpt[this.filterData[i].key]) {
							this.filterData[i].detailList = this.goodsOpt[this.filterData[i].key];
						}
					}
				}
			},

			orderbyChange(obj) {
				console.log("=======orderbyChange", 1);
				this.$refs.condition.visibleDrawer = true;
			},

			// 跳转到商品详情页
			goToDetail(item) {
				return;
				uni.navigateTo({
					url: `/pages/goods/good?id=${item.id}&formData=${JSON.stringify(item)}`,
				});
			},


			searchByName() {
				this.searchParam.name = this.name;
				this.onSearch();
			},
			async onSearch() {
				this.$api.storeStockSearch(this.searchParam).then(result => {
					this.datalist = result ? result : []
				}).catch(res => {
					// 失败进行的操作
					uni.showToast({
						title: "查询失败!",
						duration: 3000
					});
					return;
				})
			},

			addToOrderList(item) {
				this.selectGoods[item.goodsId] = {
					buyNum: 1,
					name: item.name,
					price: item.price,
					image: item.image,
					id: item.goodsId,
					stock:item.stockCurrent
				}
				this.updateSelectData();
			},

			changeValue(value) {
				if (value.buyNum === 0) {
					delete this.selectGoods[value.id];
				}
				this.updateSelectData();
			},

			updateSelectData() {
				this.options[0].info = Object.keys(this.selectGoods).length;
				uni.setStorageSync("orderGoods", this.selectGoods);
				this.sumSelectPrice();
			},

			onClick(e) {
				if (this.showSelect) {
					this.showSelect = false;
					// this.searchParam.goodIds = [];
				} else {
					this.showSelect = true;
					// this.searchParam.goodIds =  Object.keys(this.selectGoods[item.goodsId]);
					// ;
				}
				this.onSearch()
			},

			buttonClick(e) {
				// 跳转到下单界面
				uni.navigateTo({
					url: `/pages/order/storeOrder?goods=${JSON.stringify(this.selectGoods)}`,
				});
			}
		},
	};
</script>

<style lang="less" scoped>
	@import url("@/common/css/list_new.less");

	.data-item::after {
		content: " " !important;
		/* 右箭头 */
		font-size: 0rpx;
		/* 箭头大小 */
		color: #999;
		/* 箭头颜色 */
		margin-left: 0rpx;
		/* 箭头与文本的间距 */
	}

	.add-image {
		width: 50rpx;
		height: 50rpx;
	}

	.diygw-search {
		width: 755rpx !important;
	}

	.price_info {
		float: right;
		/* padding-right: 20px; */
		font-size: 14px;
		position: fixed;
		bottom: 146rpx;
		right: 40rpx;
		background-color: #fff;
		z-index: 900;
	}

	.data-list {
		padding-bottom: 200rpx !important;
	}
</style>